package coreBiz

import (
	"crypto/md5"
	"encoding/hex"
	"sort"
	"strings"

	"github.com/spf13/cast"
)

// Ksort 对map进行键的排序
func Ksort(m map[string]any) []string {
	keys := make([]string, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}
	sort.Strings(keys)
	return keys
}

// InArray 判断某一个值是否含在切片之中
func InArray(need string, haystack []string) bool {
	for _, item := range haystack {
		if item == need {
			return true
		}
	}
	return false
}
func InArrayInt(need int, haystack []int) bool {
	for _, item := range haystack {
		if item == need {
			return true
		}
	}
	return false
}

// RemoveDuplicates slice 去重，顺序不变，使用 map 去重（创建新 slice）
func RemoveDuplicates[T comparable](slice []T) []T {
	seen := make(map[T]bool)
	result := make([]T, 0, len(slice))

	for _, item := range slice {
		if !seen[item] {
			seen[item] = true
			result = append(result, item)
		}
	}

	return result
}

// RemoveDuplicatesInPlace slice 去重，顺序不变，使用 map 去重（原地修改 slice）
func RemoveDuplicatesInPlace[T comparable](slice []T) []T {
	seen := make(map[T]struct{})
	index := 0

	for _, item := range slice {
		if _, exists := seen[item]; !exists {
			seen[item] = struct{}{}
			slice[index] = item
			index++
		}
	}

	return slice[:index]
}

// ParamToSignV0 将数组按照字母排序进行md5加密 Parmmkmd5sign（原）
func ParamToSignV0(param map[string]any, key string) string {
	step1 := ParamKeySort(param)
	step2 := Md5(step1)
	step3 := step2 + key
	// 计算MD5签名
	sign := md5.Sum([]byte(step3))
	return hex.EncodeToString(sign[:])
}

func ParamToSign(param map[string]any, key string) string {
	step1 := ParamKeySort(param)
	step2 := step1 + "&key=" + key
	// 计算MD5签名
	sign := md5.Sum([]byte(step2))
	return hex.EncodeToString(sign[:])
}

// ParamKeySort 参数排序(升序)
func ParamKeySort(param map[string]any) string {
	if param != nil && len(param) > 0 {
		// 按字典序排序参数
		var keys []string
		for k := range param {
			keys = append(keys, k)
		}
		sort.Strings(keys)

		var buff strings.Builder
		for _, k := range keys {
			v := cast.ToString(param[k])
			if k == "sign" || strings.TrimSpace(v) == "" {
				continue
			}
			buff.WriteString(k + "=" + v + "&")
		}
		return strings.TrimRight(buff.String(), "&")
	}

	return ""
}

// ParamKeyRSort 参数排序(降序)
func ParamKeyRSort(param map[string]any) string {
	if param != nil && len(param) > 0 {
		// 按字典序降序参数
		var keys []string
		for k := range param {
			keys = append(keys, k)
		}
		sort.Sort(sort.Reverse(sort.StringSlice(keys)))

		var buff strings.Builder
		for _, k := range keys {
			v := cast.ToString(param[k])
			if k == "sign" || strings.TrimSpace(v) == "" {
				continue
			}
			buff.WriteString(k + "=" + v + "&")
		}
		return strings.TrimRight(buff.String(), "&")
	}

	return ""
}
